
from db import db1

class RBAC:
    def __init__(self):
        pass
    # 添加权限
    def set_role_resource(self,role_id,reslist):
        for i in reslist:
            sql = "insert into role_res values(%d,%d)"%(int(role_id),int(i))
            db1.update(sql)
    # 修改权限
    def update_role_resource(self,role_id,reslist):
        sql = "delete from role_res where role_id=%d "%(int(role_id))
        db1.update(sql)
        self.set_role_resource(role_id,reslist)

    # 删除单个权限
    def delete_role_resource(self,role_id,resourceid):
        sql = "delete from role_res where role_id=%d and resource_id=%d"%(int(role_id),int(resourceid))
        db1.update(sql)
    # 获取页面资源列表   1 为前端页面资源
    def get_pagedef_reslist(self,uid):
        sql = "select role_id from user_role where user_id=%d" % int(uid)
        res = db1.find_all(sql)
        for i in res:
            sql1 = "select r.url as url from role_res as ro inner join resource as r on ro.resource_id=r.id where ro.role_id=%d and r.type=1" % (
                int(i['role_id']))
            res1 = db1.find_all(sql1)
            lst = []
            for j in res1:
                lst.append(j['url'])
            return lst
#     获取接口资源列表’ 2 为后台资源
    def get_interface_reslist(self,uid):
        sql = "select role_id from user_role where user_id=%d" % int(uid)
        res = db1.find_all(sql)
        for i in res:
            sql1 = "select r.url as url from role_res as ro inner join resource as r on ro.resource_id=r.id where ro.role_id=%d and r.type=2" % (
                int(i['role_id']))
            res1 = db1.find_all(sql1)
            lst = []
            for j in res1:
                lst.append(j['url'])
            return lst

    # 获取所有资源列表
    def get_pagedelist(self):
        sql = "select r.id,r.name,r.url as url from  resource as r "
        res = db1.find_all(sql)
        return res



rbac = RBAC()